import path from 'path';

import type { ComponentResolver } from '../unplugin-vue-components';
import { PlatformSplitChar, walkSync } from './utils';

const primitiveStoreNames: { [key: string]: { as?: string; from: string; name?: string } } = {};

//store路径
const prefixStorePath = path.resolve(
  process.cwd(),
  `src${PlatformSplitChar}store${PlatformSplitChar}modules`,
);

//别名路径
// const aliasPath = '/src/store/modules/';

//扫描store
walkSync(prefixStorePath, ['.ts'], function (filePath: string) {
  const names = filePath.split(PlatformSplitChar);
  //app.ts ---> useAppStore
  const fileName = names[names.length - 1].split('.')[0];
  const storeName = `use${fileName[0].toUpperCase()}${fileName.substring(1)}Store`;
  const storeNameWithOut = `use${fileName[0].toUpperCase()}${fileName.substring(1)}StoreWithOut`;
  //支持别名路径，不要文件名后缀
  primitiveStoreNames[storeName] = {
    from: `${prefixStorePath}/${fileName}`,
    as: storeName,
    name: storeName,
  };
  primitiveStoreNames[storeNameWithOut] = {
    from: `${prefixStorePath}/${fileName}`,
    as: storeNameWithOut,
    name: storeNameWithOut,
    // importName: storeNameWithOut,
  };
});

// 是否modules中的store
function isGllStore(storeName: string): boolean {
  return Object.keys(primitiveStoreNames).includes(storeName);
  // return !!primitiveStoreNames[storeName] || false;
}

//本地store 导入
export function GllStoresResolver(): ComponentResolver {
  return {
    //无用
    type: 'component',
    resolve: (name) => {
      if (isGllStore(name)) return primitiveStoreNames[name];
    },
  };
}
